<!-- 花店排序 -->
<template>
    <div >
        <a-page-header
            style="border: 1px solid rgb(235, 237, 240);background:#fff"
            :title="`${storehouse}-${province}-${city}-${area}-花店排序`"
            @back="() => $router.go(-1)"
        >
        <div style="margin-bottom: 30px">
            <div id='mapContainer'></div>
        </div>  
        <div class='table-page-search-wrapper'>
            <a-form layout='inline'>
               <a-row :gutter='48'>
                    <a-col :md="8" :sm="24">
                        <a-form-item label="用户ID">
                            <a-input v-model="userId" allow-clear placeholder="请输入用户ID" />
                        </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="24">
                        <a-form-item label="手机号">
                            <a-input v-model="phone" allow-clear placeholder="请输入用户手机号" />
                        </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="24">
                        <a-form-item label="花店名称">
                            <a-input v-model="shopName" allow-clear placeholder="请输入花店名称" />
                        </a-form-item>
                    </a-col>
                    <!-- <a-col :md="8" :sm="24">
                        <a-form-item label="城市">
                            <a-input v-model="city" allow-clear placeholder="请输入城市" />
                        </a-form-item>
                    </a-col> -->
                    <a-col :md="8" :sm="24">
                        <a-form-item label="是否已经排序">
                            <a-select v-model="rankStatus" placeholder="请选择" allowClear @change="getData">
                                <a-select-option v-for="item in rankStatusList" :key="item.id" :value="item.id">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="24">
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item >
                            <a-button type='primary' @click="getData">查询</a-button>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>

        <a-table rowKey="userId" bordered :loading="isload" :columns="columns" :data-source="dataList" @change="handleTableChange" :pagination="{ pageSize: 10, total: total ,showSizeChanger: true,pageSize: size}" size="small" >
            <template slot="province" slot-scope="province, record">
                <div>{{province}}-{{record.city}}-{{record.region}}</div>
            </template>
            <template slot="rank" slot-scope="rank, record">
                <editable-cell :text="record.rank" @change="onCellChange(record.id, 'rank', $event)" />
            </template>
        </a-table>
        </a-page-header>
    </div>
</template>

<script>
import { columns } from './table';
import { queryShoppingRankRecord , updateShoppingRankRecord } from '@/api/newMall';


const EditableCell = {
    template: `
        <div class="editable-cell">
            <div v-if="editable" class="editable-cell-input-wrapper">
            <a-input :value="value" @change="handleChange" @pressEnter="check" /><a-icon
                type="check"
                class="editable-cell-icon-check"
                @click="check"
            />
            </div>
            <div v-else class="editable-cell-text-wrapper">
            {{ text || ' ' }}
            <a-icon type="edit" class="editable-cell-icon" @click="edit" />
            </div>
        </div>
        `,
    props: {
        text: Number,
    },
    data() {
        return {
        value: this.text,
        editable: false,
        };
    },
    methods: {
        handleChange(e) {
            const value = e.target.value;
            this.value = value;
        },
        check() {
            this.editable = false;
            this.$emit('change', this.value);
        },
        edit() {
            this.value  = this.text;
            this.editable = true;
        },
    },
};

export default {
    data () {
        return {
            brandId: this.global.brandId,
            storehouse: JSON.parse(localStorage.getItem('storehouseName')),
            isload: false,
            dataList: [],
            columns,
            total: 0,
            page: 1,
            size: 10,
            phone: '',
            isload: false,
            userId: '',
            shopName: '', // 花店名称
            city: JSON.parse(localStorage.getItem('city')), // 城市
            province: JSON.parse(localStorage.getItem('province')), // 城市
            area: JSON.parse(localStorage.getItem('area')), // 城市
            rankStatus: 1,
            rankStatusList: [
                { id: 1, name: '已排序'},
                { id: 0, name: '未排序'},
            ],
        };
    },
    components: {
        EditableCell,
    },
    created(){
    },
    mounted(){
        this.getData();
    },
    methods: {
        // 查询花店信息
        getData(){
            let _this = this
            const params = {
                'brandId':_this.brandId,
                'phone':_this.phone,
                'userId':_this.userId,
                'shopName': _this.shopName,
                'city': _this.city,
                'region': _this.area,
                'province': _this.province,
                'rankStatus':_this.rankStatus,
                'page':_this.page - 1,
                'size':_this.size,
            }
            queryShoppingRankRecord(params)
            .then(res=>{
                if(res.success){
                    _this.dataList = res.data.content
                    _this.total = res.data.totalElements
                    _this.init();
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 分页
        handleTableChange(pagination, filters, sorter) {
            console.log(pagination);
            this.page = pagination.current;
            this.size = pagination.pageSize;
            this.getData()
        },
        onCellChange(key, dataIndex, value) {
            const dataSource = [...this.dataList];
            const target = dataSource.find(item => item.id === key);
            // if (target) {
            //     target[dataIndex] = value;
            //     this.dataSource = dataSource;
            // }
            let _this = this;
            console.log(key,dataIndex,value,'oncellchange')
            const params = {
                'id': key,
                'rank': value,
                'userId': target.userId,
            }
            updateShoppingRankRecord(params)
            .then(res => {
                if(res.success){
                    _this.getData();
                    _this.$notification['success']({
                        message: '提示',
                        description: "修改成功",
                        duration: 8,
                    })
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 地图初始化
        init() {
            var SVG_NS = 'http://www.w3.org/2000/svg';
            var colorList = ['#7AF4FF', '#67D7FF', '#52B5FF', '#295BFF'];
            let _this = this;
            if(_this.rankStatus == '2'){
                return;
            }
            const pionts = [];
            var array = this.dataList;
            for (let index = 0; index < array.length; index++) {
                const item = array[index];
                if(item.latitude){
                    var obj = {
                        'position': new TMap.LatLng(item.latitude,item.longitude),
                        'id': item.rank,
                    }
                    pionts.push(obj)
                }
            }
            var drawContainer = document.getElementById('mapContainer');
            drawContainer.innerHTML  = '';
            console.log(drawContainer,'drawContainer')
            // 自定义图层
            function SvgMarker(options) {
                TMap.DOMOverlay.call(this, options);
            }
            SvgMarker.prototype = new TMap.DOMOverlay();
            // 初始化
            SvgMarker.prototype.onInit = function (options) {
                this.options = options.options;
                this.map = options.map;
            };
            // 销毁时需解绑事件监听
            SvgMarker.prototype.onDestroy = function () {
                if (this.onClick) {
                this.dom.removeEventListener(this.onClick);
                }
            };
            // 创建DOM元素，返回一个DOMElement，使用this.dom可以获取到这个元素
            SvgMarker.prototype.createDOM = function () {
                var svg = document.createElementNS(SVG_NS, 'svg');
                svg.id = 'svgDom';
                svg.setAttribute('width', mapContainer.offsetWidth);
                svg.setAttribute('height', mapContainer.offsetHeight);
                svg.style.cssText = 'position:absolute;top:0px;left:0px;';
                var group = []; // 定义g元素数组
                var circleShape = []; // 定义circle元素数组
                var textShape = []; // 定义text元素数组
                // 遍历传入参数，创建同等数量的svg下元素节点并绑定事件
                for (var i = 0; i < this.options.length; i++) {
                    var createCenter = this.map.projectToContainer(this.options[i].position);
                    group[i] = document.createElementNS(SVG_NS, 'g');
                    
                    // 在中心创建一个圆形
                    circleShape[i] = document.createElementNS(SVG_NS, 'circle');
                    circleShape[i].setAttribute('style', 'fill: blue;stroke:#FFFFFF;opacity:0.9;');
                    circleShape[i].setAttribute('cx', createCenter.x);
                    circleShape[i].setAttribute('cy', createCenter.y);
                    circleShape[i].setAttribute('r', 12);
                    group[i].appendChild(circleShape[i]);

                    // 绘制文字
                    textShape[i] = document.createElementNS(SVG_NS, 'text');
                    textShape[i].setAttribute('x', createCenter.x);
                    textShape[i].setAttribute('y', createCenter.y + 3); // +5是为了让文字向下偏移5像素，使文字居中
                    textShape[i].setAttribute('text-anchor', 'middle');
                    textShape[i].setAttribute('fill', '#FFFFFF');
                    textShape[i].innerHTML = this.options[i].id + 1;
                    svg.appendChild(group[i]);
                    group[i].appendChild(textShape[i]);
                    this.onMouseEnter = function(e) {
                        // DOMOverlay继承自EventEmitter，可以使用emit触发事件
                        // 动态修改circle颜色，所以选择传入circle节点
                        this.emit('mouseenter', e.target.firstChild);
                    }.bind(this);
                    this.onMouseLeave = function(e)  {
                        this.emit('mouseleave', e.target.firstChild);
                    }.bind(this);
                    group[i].addEventListener('mouseenter', this.onMouseEnter);
                    group[i].addEventListener('mouseleave', this.onMouseLeave);
                }
                return svg;
            };

            // 更新DOM元素，在地图移动/缩放后执行
            SvgMarker.prototype.updateDOM = function () {
                if (!this.map) {
                return;
            }

            // 经纬度坐标转容器像素坐标
            for (var j = 0; j < this.options.length; j++) {
                var pixel = this.map.projectToContainer(this.options[j].position);
                var updateCenter = this.map.projectToContainer(this.options[j].position);
                this.dom.children[j]
                    .getElementsByTagName('circle')[0]
                    .setAttribute('cx', updateCenter.x);
                this.dom.children[j]
                    .getElementsByTagName('circle')[0]
                    .setAttribute('cy', updateCenter.y);
                this.dom.children[j]
                    .getElementsByTagName('text')[0]
                    .setAttribute('x', updateCenter.x);
                this.dom.children[j]
                    .getElementsByTagName('text')[0]
                    .setAttribute('y', updateCenter.y + 5);
                }
            };
            console.log(pionts,'pionts')
            // var center = new TMap.LatLng(39.984104, 116.307503);//设置中心点坐标/
            var center = pionts.length > 0 ? pionts[0].position : new TMap.LatLng(39.984104, 116.307503);
            var map = new TMap.Map(drawContainer, {
                zoom: 9,
                pitch: 40,
                center: center,
                draggable: true,
                scrollable: true,
                mapStyleId: "style 1"
            });
            //  = map;/s

            var marker = new SvgMarker({
                map: map,
                options: pionts
            });
            map.res
            marker.on('mouseenter', function(e) {
                e.setAttribute('style', 'fill: red;stroke:red; opacity:0.9;');
            });
            marker.on('mouseleave', function(e) {
                e.setAttribute('style', 'fill: blue;stroke:#FFFFFF;opacity:0.9;');
            });
            // 监听地图容器变化，动态修改svg图层大小，防止更新时元素移出svg图区
            map.on('resize', function() {
                document.getElementById('svgDom').setAttribute('width', mapContainer.offsetWidth);
                document.getElementById('svgDom').setAttribute('height', mapContainer.offsetHeight);
            })

            // 创建点聚合实例
            // var markerCluster = new TMap.MarkerCluster({
            //     id: 'cluster',
            //     map: map,
            //     enableDefaultStyle: true, // 启用默认样式
            //     minimumClusterSize: 2, // 形成聚合簇的最小个数
            //     geometries: pionts,
            //     zoomOnClick: true, // 点击簇时放大至簇内点分离
            //     gridSize: 60, // 聚合算法的可聚合距离
            //     averageCenter: true, // 每个聚和簇的中心是否应该是聚类中所有标记的平均值
            //     maxZoom: 10 // 采用聚合策略的最大缩放级别
            // });
        },
    }
}


</script>
<style scoped>
#mapContainer{
    width: 100%;
    height: 400px;
}
</style>